with NAL_Analyzer;
with AC3_Analyzer;
with Interfaces; use Interfaces;
with Logging;

package body Controller is
   NAL : PES.PES_Buffer_Type(8*1024*1024);
   Frame : PES.PES_Buffer_Type(8*1024);
   Frame_PTS_Counter : Unsigned_32 := 0;

   procedure Start(In_File : in IO.File_Type; Out_FIle : in IO.File_Type) is
   begin
      NAL_Analyzer.Read(NAL.Access_Unit, In_File);
         while (NAL.Size > 0) loop
            NAL_Analyzer.Read(NAL.Access_Unit, In_File);
         end loop;
   end Start;

   procedure StartAC3(In_File : in IO.File_Type; Out_FIle : in IO.File_Type) is
   begin
      Logging.Start_Timer;
      Logging.Start_Counter;

      loop
         AC3_Analyzer.Read(Frame.Access_Unit, In_File);
         exit when Frame.Access_Unit.Size = 0;

         --AC3 frames are 32ms in length, or 2880 ticks of the 90KHz clock. The resulting frame rate is 31.25 fps.
         Frame_PTS_Counter := Frame_PTS_Counter + 2880;
         PES.PES_Generator(Frame, Frame_PTS_Counter);
         Write(Frame, Out_FIle);
         Logging.Increment_Counter;
      end loop;

      Logging.Stop_Counter;
      Logging.Stop_Timer;
   end StartAC3;

   procedure Write(Buffer : in PES.PES_Buffer_Type; File : in IO.File_Type) is
   begin
      for I in 1..Buffer.Size loop
         PES.PES_Header_Type'Write(File.File_Access, Buffer.PES_Units(I).Header);
         PES.PES_Header_Extension_Type'Write(File.File_Access, Buffer.PES_Units(I).Extension);
         IO.Byte_Array'Write(File.File_Access, Buffer.Access_Unit.Byte_Buffer(Buffer.PES_Units(I).Start_Pos .. Buffer.PES_Units(I).Start_Pos + Buffer.PES_Units(I).Size - 1));
         --IO.Byte_Array'Write(File.File_Access, Buffer.Byte_Buffer);
      end loop;
   end Write;
end Controller;